package com.sunshine.user.controller;


import com.sunshine.user.dto.UserRegisterDTO;
import com.sunshine.user.entity.Users;
import com.sunshine.user.service.UsersService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import sunshine.commcon.util.entity.Result;


import javax.annotation.Resource;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class LoginController {

    private static final Logger log = LoggerFactory.getLogger(LoginController.class);

    @Resource
    private UsersService usersService;

    @GetMapping("/test")
    public String test() {
        return "hello sunshine";
    }

    @PostMapping("/register")
    public Result<Boolean> register(@RequestBody UserRegisterDTO userRegisterDTO) {
        // 判断是否启用INFO级别日志
        if (log.isInfoEnabled()) {
            log.info("开始处理用户注册请求，用户名：{}", userRegisterDTO.getUsername());
        }
        
        // 调用服务层进行注册
        Result<Boolean> result = usersService.register(userRegisterDTO);
        
        // 判断是否启用INFO级别日志
        if (log.isInfoEnabled()) {
            log.info("用户注册处理完成，用户名：{}，注册结果：{}", userRegisterDTO.getUsername(), result.getSuccess());
        }
        
        return result;
    }

    @PostMapping("/login")
    public Result<Users> login(@RequestBody(required = false) Map<String, String> loginData) {
        String username = null;
        String password = null;
        
        if (loginData != null) {
            username = loginData.get("username");
            password = loginData.get("password");
        }
        
        if (log.isInfoEnabled()){
            log.info("开始处理用户登录请求，用户名：{}", username);
        }
        Result<Users> login = usersService.login(username, password);
        if (log.isInfoEnabled()){
            log.info("用户登录处理完成，用户名：{}，登录结果：{}", username, login.getSuccess());
        }
        return login;
    }


    @PostMapping("/updatePassword")
    public Result<Boolean> updatePassword(@RequestBody UserRegisterDTO userRegisterDTO) {

        if (log.isInfoEnabled()) {
            log.info("开始处理用户修改密码请求，用户名：{}", userRegisterDTO.getUsername());
        }
        Result<Boolean> booleanResult = usersService.updatePassword(userRegisterDTO);
        if (log.isInfoEnabled()){
            log.info("用户修改密码处理完成，用户名：{}，修改结果：{}", userRegisterDTO.getUsername(), booleanResult.getSuccess());
        }
        return booleanResult;
    }




}